﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using System.Resources;
using System.Web.Security;
using System.Web.Profile;
using EHTWebsite.Code;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Data;
using EHTWebsiteProject.Code.Entity;
using EHTWebsiteProject.Code.BLL;

namespace EHTWebsiteProject
{
    public partial class IndexRegister : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataSet dsRegion = RegionProvider.GetRegions();
                this.ddlRegion.DataValueField = "RegionID";
                this.ddlRegion.DataTextField = "RegionName";
                this.ddlRegion.DataSource = dsRegion;
                this.ddlRegion.DataBind();
                this.ddlRegion.Items.Insert(0, new ListItem("-- Velg Region --", "-1"));

                DataSet dsLevelServices = ServiceLevelsProvider.GetServiceLevels();
                this.ddlServiceLevel.DataValueField = "SeviceLevelID";
                this.ddlServiceLevel.DataTextField = "Description";
                ddlServiceLevel.DataSource = dsLevelServices;
                ddlServiceLevel.DataBind();
                this.ddlServiceLevel.Items.Insert(0, new ListItem("-- LevelService --", "-1"));
            }
        }

        private Boolean ValidateData()
        {
            String message = "";
            Boolean isSuccess = true;

            if (ddlRegion.SelectedValue == "-1")
            {
                message += "Velg Region <br />";
                isSuccess = false;
            }
            if (ddlServiceLevel.SelectedValue == "-1")
            {
                message += "Velg Service Level <br />";
                isSuccess = false;
            }
            if (this.txtPassword.Text.Trim().Length < 6)
            {
                message += "Passord må ha lengh >= 6";
                isSuccess = false;
            }

            if (!isSuccess)
                ltrMessage.Text = message;

            return isSuccess;
        }

        //Sinh chuỗi ngẫu nhiên
        private string RandomString()
        {
            string strString = "abcdefghijklmnopqrstuvwxyz0123456789";
            Random random = new Random();
            int randomCharIndex = 0;
            char randomChar;
            string captcha = "";
            for (int i = 0; i < 30; i++)
            {
                randomCharIndex = random.Next(0, strString.Length - 1);
                randomChar = strString[randomCharIndex];
                captcha += Convert.ToString(randomChar);
            }
            return captcha;
        }
       
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
                return;

            Page.Validate();

            if (Page.IsValid)
            {
                String userName = this.txtEmail.Text;
                String password = this.txtPassword.Text;
                String email = this.txtEmail.Text;
                MembershipUser theUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);

                //trường hợp User Name chưa tồn tại mới cho đăng kí
                if (theUser == null)
                {
                    theUser = Membership.CreateUser(userName, password, email);// tạo user
                    Roles.AddUserToRole(userName, HangSo.ROLE_USER); // thiết định vào nhóm Customer
                    //thiết định các thông tin cần thiết
                    ProfileBase theProfile = ProfileBase.Create(theUser.UserName);
                    theProfile.SetPropertyValue("FirstName", this.txtFirstName.Text.Trim());
                    theProfile.SetPropertyValue("LastName", this.txtLastName.Text.Trim());
                    theProfile.SetPropertyValue("Age", this.txtAge.Text.Trim());
                    theProfile.SetPropertyValue("Phone", this.txtPhone.Text.Trim());
                    theProfile.SetPropertyValue("Fax", this.txtFax.Text.Trim());
                    theProfile.SetPropertyValue("Address", this.txtAddress.Text.Trim());
                    theProfile.SetPropertyValue("City", this.txtCity.Text.Trim());
                    theProfile.SetPropertyValue("RegionID", Int32.Parse(this.ddlRegion.SelectedValue));
                    theProfile.SetPropertyValue("ZipCode", this.txtZipCode.Text.Trim());
                    theProfile.SetPropertyValue("Email", this.txtEmail.Text.Trim());
                    theProfile.SetPropertyValue("SignatureUrl", "");
                    if (Int32.Parse(this.ddlServiceLevel.SelectedValue) == -1)
                    {
                        theProfile.SetPropertyValue("ServiceLevelID", 0);
                    }
                    else
                        theProfile.SetPropertyValue("ServiceLevelID", Int32.Parse(this.ddlServiceLevel.SelectedValue));
                    theProfile.SetPropertyValue("ToltalAccount", float.Parse("0"));
                    theProfile.SetPropertyValue("StatusActive", 0);
                    string StringActive = RandomString();
                    theProfile.SetPropertyValue("StringActive", StringActive);
                    theProfile.Save();// lưu thông tin cần thiết

                    //lưu thông tin vào tblServicesLevelEffect
                    try
                    {
                        ServicesLevelEffect theServiceLevelsEffect = new ServicesLevelEffect();
                        theServiceLevelsEffect.CustomerID = theUser.ProviderUserKey.ToString();
                        theServiceLevelsEffect.ServicesLevelCostCurrent = 0;
                        theServiceLevelsEffect.DateEffect = DateTime.Parse("");
                        ServiceLevelsProvider.IUServiceLevelsEffect(theServiceLevelsEffect, true);
                    }
                    catch
                    {
                    }
                    
                    //Gửi mail  
                    ThongTinCongTy theThongTinCongTy = ThongTinCongTyProvider.GetThongTinCongTyByCongTyID(1);
                    String messageSendMail = "Send mail success";
                    try
                    {
                        SmtpClient SmtpServer = new SmtpClient();
                        //SmtpServer.Credentials = new System.Net.NetworkCredential(theThongTinCongTy.Email, theThongTinCongTy.EmailPass);
                        SmtpServer.Credentials = new System.Net.NetworkCredential("ktuoc@yahoo.com", "thinh321");
                        Boolean yahoovn = theThongTinCongTy.Email.Contains("yahoo.com.vn");
                        Boolean yahoo = theThongTinCongTy.Email.Contains("yahoo.com");
                        Boolean gmail = theThongTinCongTy.Email.Contains("gmail.com");
                        if (yahoo == true)
                        {
                            SmtpServer.Host = "smtp.mail.yahoo.com";
                            SmtpServer.Port = 587;
                        }
                        else if (yahoovn == true)
                        {
                            SmtpServer.Host = "smtp.mail.yahoo.com.vn";
                            SmtpServer.Port = 587;
                        }
                        else
                        {
                            SmtpServer.Host = "smtp.gmail.com";
                            SmtpServer.Port = 587;
                            SmtpServer.EnableSsl = true;
                        }
                        MailMessage mail = new MailMessage();

                        mail.From = new MailAddress(theThongTinCongTy.Email, "Re-Sale");
                        mail.To.Add(this.txtEmail.Text.Trim());
                        mail.Subject = "Aktiv konto";
                        mail.Body = "Takk for register! Klikk for å linken under for å aktivere kontoen: \n";
                        //mail.Body += "http://localhost:2423/ActiveAccountSuccess.aspx?user=" + this.txtEmail.Text.Trim() + "&active=" + StringActive;
                        mail.Body += "http://localhost:2423/AktiveringKontoSuksess-" + this.txtEmail.Text.Trim() + "-" + StringActive + ".html";
                        mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                        mail.ReplyTo = new MailAddress(theThongTinCongTy.Email);
                        SmtpServer.Send(mail);
                    }
                    catch (Exception ex)
                    {
                        messageSendMail = "Send email error " + ex.Message;
                        //Response.Redirect("RegisterConfirmSuccess.aspx?message=" + messageSendMail);
                        Response.Redirect("BekreftRegistrerSuksess-" + messageSendMail + ".html");
                    }
                    //Response.Redirect("RegisterConfirmSuccess.aspx?message=" + messageSendMail);
                    Response.Redirect("BekreftRegistrerSuksess-" + messageSendMail + ".html");
                }
                //tồn tại rồi thì hiển thị thông báo
                else
                {
                    ltrMessage.Text = "Denne E-post er alredy utganger";
                    this.txtEmail.Focus();
                }
            }
        }
    }
}